﻿#ifndef QLYVIDEOWRITER_H
#define QLYVIDEOWRITER_H

#include "QlyAVFormatContext.h"
#include "QlyAVCodecContext.h"
#include "QlyAVCodec.h"

#include <QImage>
#include <QVideoFrame>
#include <QTime>
#include <QTimer>
class QlyVideoWriter: public QObject
{
    Q_OBJECT
public:
    QlyVideoWriter();
    void setMaxRecordTime(int s) {m_timeout = s * 1000;}
    bool setAVCodecID(AVCodecID id);
    void setTimeBase(AVRational timebase) {m_time_base = timebase;}
    bool openFile(QString url);
public slots:
    /**
     * @brief setQImage 将 Image 存入视频
     * @param image
     * @param pts 以 ms 为单位，第一帧为 0. 如果 pts < 0 ，则自动根据当前时间填充 pts
     * @return
     */
    bool setQImage2(const QImage &image, int pts);
    bool setQImage(const QImage &image);
    bool setVideoFrame(QVideoFrame &videoframe, int pts);
    bool close();

private slots:
    void timeout();
protected:
    bool writeFrame(const QlyAVFrame &frame);
    bool initFile(enum AVCodecID codec_id);
    void initStreamParameters(AVStream *stream);
    void updatePts(int &pts);


    QlyAVFormatContext m_videoContext;
    QlyAVCodec m_codec;
    QlyAVCodecContext m_codecContext;
    QlyAVStream m_stream;

    QQueue<QlyAVPacket> m_packetQueue;

    AVCodecID m_codecID = AV_CODEC_ID_MPEG4;
    AVPixelFormat m_format = AV_PIX_FMT_YUV420P;
    AVRational m_time_base = {1, 1000};
    int m_count = 0;

    int64_t m_bit_rate = 10000000;
    int m_width = 0;
    int m_height = 0;

    QTime m_startTime;
    bool m_recording = false;
    QTimer m_timer;
    int m_timeout = 1000 * 1800; // 默认保存半个小时
};

#endif // QLYVIDEOWRITER_H
